﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using com.subb.WebInformation;
using WebsiteUI.ActionFilters;
using WebsiteUI.Extensions;
using WebEntities;
using WebEntities.Models.Framework;
using com.subb.WebFramework;
using WebsiteUI.Models;

namespace WebsiteUI.Controllers
{
    public class HomeController : Controller
    {
        [OutputCache(CacheProfile = "Cache15Mins")]
        public ActionResult Index()
        {
            WI_NewsDAL ndal = new WI_NewsDAL();
            //获取通知公告前4条
            //List<WI_News> bulList = CommonFn.GetNews("BulletinID", "HomePage_Bulletin", 0, 4, 600);
            List<WI_News> list1 = ndal.GetAllNews(CommonFn.GetContentID("BulletinID"), 0, 4);
            ViewBag.BulletinID = CommonFn.GetContentID("BulletinID");
            ViewBag.BulletinList = list1;

            //获取协会动态前4条
            //List<WI_News> unionNewsList = CommonFn.GetNews("UnionNewsID", "HomePage_UnionNews", 0, 4, 600); ;
            List<WI_News> list2 = ndal.GetAllNews(CommonFn.GetContentID("UnionNewsID"), 0, 4);
            ViewBag.UnionNewsID = CommonFn.GetContentID("UnionNewsID");
            ViewBag.UnionNewsList = list2;

            //获取行业信息前3条
            //List<WI_News> induNewsList = CommonFn.GetNews("IndustryNewsID", "HomePage_IndustryNews", 0, 3, 600); ;
            List<WI_News> list3 = ndal.GetAllNews(CommonFn.GetContentID("IndustryNewsID"), 0, 3);
            ViewBag.IndustryNewsID = CommonFn.GetContentID("IndustryNewsID");
            ViewBag.IndustryNewsList = list3;

            //获取1条行业论文信息
            List<WI_News> list4 = ndal.GetAllNews(CommonFn.GetContentID("IndustryDocID"), 0, 1);
            ViewBag.IndustryDocID = CommonFn.GetContentID("IndustryDocID");
            ViewBag.TechNewsList = list4;

            //获取1条行业趋势信息
            List<WI_News> list5 = ndal.GetAllNews(CommonFn.GetContentID("IndustryTrendID"), 0, 1);
            ViewBag.IndustryTrendID = CommonFn.GetContentID("IndustryTrendID");
            ViewBag.IndustryTrendList = list5;

            //获取1条科研院所信息
            List<WI_News> list6 = ndal.GetAllNews(CommonFn.GetContentID("ResearchRoomID"), 0, 1);
            ViewBag.ResearchRoomID = CommonFn.GetContentID("ResearchRoomID");
            ViewBag.ResearchRoomList = list6;

            //专家人物滚动
            int PageTotal = 0;
            WI_ExpertsDAL DAL = new WI_ExpertsDAL();
            List<WI_Experts> list7 = DAL.GetAllExpertsByView(0, 0, 10, out PageTotal);
            ViewBag.ExpertsList = list7;

            ViewBag.UnionMookID = CommonFn.GetContentID("UnionMookID");
            ViewBag.KnowledgeID = CommonFn.GetContentID("KnowledgeID");

            return View();
        }
        /// <summary>
        /// 网站通用头部（LOGO,头部信息，导航菜单）
        /// </summary>
        /// <returns></returns>
        public ActionResult Head()
        {
            object data = CommonFn.GetCacheData("TopNavMenu");
            List<FW_Menu> menuList;
            //List<FW_MenuItem> mitemList;
            if (data == null)
            {
                FW_MenuDAL mdal = new FW_MenuDAL();
                menuList = mdal.GetAllMenusByType(UIMenu.FrontMenuType);
                CommonFn.CacheData("TopNavMenu", menuList, 3600);
            }
            else
            {
                menuList = data as List<FW_Menu>;
            }
            //加载登录用户资料，放在Session
            if (Request.IsAuthenticated && Session["LoginMember"] == null)
            {
                FW_MemberDAL mdal = new FW_MemberDAL();
                FW_Member member = mdal.GetMember(HttpContext.User.Identity.Name);
                Session["LoginMember"] = member;
            }
            return PartialView(menuList);
        }
        /// <summary>
        /// 网站底部
        /// </summary>
        /// <returns></returns>
        [CtrlActionOutputCache("Cache1Hour")]
        public ActionResult Footer()
        {
            return PartialView();
        }

        /// <summary>
        /// 友情链接
        /// </summary>
        /// <returns></returns>
        [CtrlActionOutputCache("Cache30Mins")]
        public ActionResult FriendLink()
        {
            WI_FriendlyLinkDAL fdal = new WI_FriendlyLinkDAL();
            List<WI_FriendlyLink> flinkList = fdal.GetAllFriendlyLink();
            return PartialView(flinkList);
        }

        public ActionResult Login(string repath)
        {
            ViewBag.ReturnPath = repath ?? "/";
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel lmodel, string repath)
        {
            ViewBag.ReturnPath = repath;
            if (string.IsNullOrWhiteSpace(lmodel.UserName))
            {
                ViewBag.Msg = "请输入帐号";
            }
            else if (string.IsNullOrEmpty(lmodel.Password))
            {
                ViewBag.Msg = "请输入密码";
            }
            else
            {
                FW_MemberDAL mdal = new FW_MemberDAL();
                DateTime dtLastLogin;
                MemberVerifyResult vresult = mdal.VerifyMember(lmodel.UserName, lmodel.Password, out dtLastLogin);
                if (vresult == MemberVerifyResult.Success)
                {
                    FormsAuthentication.SetAuthCookie(lmodel.UserName, lmodel.RememberMe);
                    FW_Member member = mdal.GetMember(lmodel.UserName);
                    Session["LoginMember"] = member;
                    Session["LastLoginTime"] = dtLastLogin.ToString();
                    mdal.LoginSuccess(lmodel.UserName);
                    return Redirect(repath);
                }
                else if (vresult == MemberVerifyResult.Locked)
                {
                    ViewBag.Msg = "您的帐号已被冻结";
                }
                else
                {
                    ViewBag.Msg = "您的帐号或者密码不正确。";
                }
            }
            return View();
        }

        public ActionResult Logout()
        {
            if (Request.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
            }
            return RedirectToAction("Index");
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel rmodel)
        {
            string msg;
            try
            {
                bool vresult = rmodel.VerifyModel(out msg);
                if (vresult)
                {
                    FW_MemberDAL mdal = new FW_MemberDAL();
                    string userName = rmodel.UserName.Trim();
                    string email = userName;
                    string nickName = rmodel.NickName.Trim();
                    Member newMem = new Member
                    {
                        MemberID = userName,
                        MemPasswd = rmodel.Password,
                        //暂时使用用户ID作为昵称
                        NickName = nickName,
                        Email = email,
                        //用户状态默认活动
                        MemStatus = 1,
                        MemType = (byte)MemberType.Website,
                        //默认未认证邮箱
                        EmailValid = 0
                    };
                    mdal.CreateMember(newMem);
                    EmailUtils eu = new EmailUtils();
                    eu.SendVerifyMail(userName, email, Request.UserHostAddress);
                    ViewBag.Msg = "注册成功，请确认邮件！";
                    TempData["MemberID"] = userName;
                    return RedirectToAction("ValidEmail");
                }
                else
                {
                    ViewBag.Msg = msg;
                }
            }
            catch
            {
                ViewBag.Msg = "注册出错，请与网站管理员联系。";
            }
            return View();
        }

        [HttpPost]
        public ActionResult CheckUserName(string userName)
        {
            //result为真说明用户名已存在
            bool result = true;
            string uname = userName.Trim();
            if (!string.IsNullOrWhiteSpace(uname))
            {
                FW_MemberDAL mdal = new FW_MemberDAL();
                result = mdal.HasExistMemberID(userName);
            }
            return Json(new { result = result });
        }

        [HttpPost]
        public ActionResult CheckNickName(string nickName)
        {
            //result为真说明用户名已存在
            bool result = true;
            string nname = nickName.Trim();
            if (!string.IsNullOrWhiteSpace(nname))
            {
                FW_MemberDAL mdal = new FW_MemberDAL();
                result = mdal.HasExistNickName(nickName);
            }
            return Json(new { result = result });
        }

        /// <summary>
        /// 邮箱验证页面
        /// </summary>
        /// <returns></returns>
        public ActionResult ValidEmail()
        {
            if (!Request.IsAuthenticated)
            {
                string userName = (string)TempData["MemberID"] ?? (string)Session["MemberID"];
                Session["MemberID"] = userName ?? string.Empty;
            }
            else
            {
                FW_MemberDAL mdal = new FW_MemberDAL();
                FW_Member member = mdal.GetMember(HttpContext.User.Identity.Name);
                ViewBag.EmailValid = member.EmailValid;
                ViewBag.Email = member.Email;
            }
            return View();
        }

        /// <summary>
        /// 邮箱确认页面
        /// </summary>
        /// <returns></returns>
        public ActionResult RegConfirm(string id)
        {
            bool result = false;
            string memId = string.Empty;
            if (!string.IsNullOrWhiteSpace(id))
            {
                FW_MemberDAL mdal = new FW_MemberDAL();
                if (mdal.VerfiyEmailVcode(id, out memId))
                {
                    result = true;
                    ViewBag.ValidMsg = "邮箱验证成功！";
                    mdal.EmailBinding(memId);
                }
                else
                {
                    ViewBag.ValidMsg = "您的验证邮件已失效，请重新发送验证邮件！";
                }
            }
            else
            {
                ViewBag.ValidMsg = "验证邮件有误，无法正确识别。";
            }
            ViewBag.Valid = result;
            return View();
        }

        /// <summary>
        /// 重新发送验证邮件
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public ActionResult ResendValMail(string email)
        {
            string msg = string.Empty;
            string memId = Request.IsAuthenticated ? email : (string)Session["MemberID"];
            EmailUtils eu = new EmailUtils();
            if (string.IsNullOrWhiteSpace(email))
            {
                msg = "请输入验证邮箱地址。";
            }
            else if (!eu.CheckEmailFormat(email))
            {
                msg = "邮箱地址格式不正确。";
            }
            else if (string.IsNullOrWhiteSpace(memId))
            {
                msg = "请登录网站后再发送验证邮件。";
            }
            else
            {
                FW_MemberDAL mdal = new FW_MemberDAL();
                if (mdal.CheckResendValidEmail(memId, email, Request.UserHostAddress, out msg))
                {
                    eu.SendVerifyMail(memId, email, Request.UserHostAddress);
                    msg = "请注意查收您的邮箱，已发送一封确认邮件到您的邮箱！";
                }
            }
            return Json(new { Msg = msg });
        }
        /// <summary>
        /// 网站地图
        /// </summary>
        /// <returns></returns>
        
        public ActionResult Map()
        {
            object data = CommonFn.GetCacheData("TopNavMenu");
            List<FW_Menu> menuList;
            //List<FW_MenuItem> mitemList;
            if (data == null)
            {
                FW_MenuDAL mdal = new FW_MenuDAL();
                menuList = mdal.GetAllMenusByType(UIMenu.FrontMenuType);
                CommonFn.CacheData("TopNavMenu", menuList, 3600);
            }
            else
            {
                menuList = data as List<FW_Menu>;
            }
            return View(menuList);
        }

    }
}
